package com.ivo.sys.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ivo.biz.OperationForeman;
import com.ivo.biz.Permissions;
import com.ivo.core.hibernate.HibernateInvoker;
import com.ivo.util.StringUtil;

/**
 * 
 *
 * @author Minkey Wang
 * @version 2017年7月13日
 */
@Service
public class UserService {
	@Autowired
	UserManager userManager;
	
    @Autowired
    private HibernateInvoker hibernateInvoker;
	
	public User getUser(String username) {
		String hql = "select u from User u  where u.isValid=true and u.user_id=?0 ";
		return userManager.findUnique(hql, username);
	}
	public List list(String emp_id, String condition) {
	   	List<Object> params = new ArrayList<>();
        StringBuilder hql = new StringBuilder("select new map(d.id as id, d.user_id as user_id, d.user_name as user_name,")
                .append(" d.password as password ) from User d where d.isValid is true");
        int paramPosition = 0;
        if (StringUtil.isNotEmpty(emp_id)) {
            String placeholder = "?" + paramPosition++;
            hql.append(" and d.user_id = ").append(placeholder);
            params.add(emp_id);
        }
        if (StringUtil.isNotEmpty(condition)) {
            hql.append(" and (").append(condition).append(")");
        }
        String queryString = hql.toString();
        List list = hibernateInvoker.find(Map.class, queryString, params.toArray());
    	List<Map<String, Object>> listTemp = new ArrayList<Map<String, Object>>();
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("allTotal", list.size());
    	map.put("user", list);
    	listTemp.add(map);
		return listTemp;
	}

	public Role getRoleByUser(String user_id){
		String hql ="select r from User u join UserRole k on u.id = k.user_fk"
				    +" join Role r on k.role_fk=r.id where u.isValid=true and k.isValid=true and r.isValid=true and u.user_id =?0";
		return (Role) hibernateInvoker.findUnique(hql, user_id);
	}
	public Role getRoleByUser(String user_id,String  roleName){
		String hql ="select r from User u join UserRole k on u.id = k.user_fk"
				    +" join Role r on k.role_fk=r.id where u.isValid=true and k.isValid=true and r.isValid=true and u.user_id =?0 AND r.name = ?1";
		return (Role) hibernateInvoker.findUnique(hql, user_id,roleName);
	}
	public OperationForeman getOpeIDByUser(String user_id){
		String hql ="from OperationForeman op where op.foreman_id =?0";
		return (OperationForeman) hibernateInvoker.findUnique(hql, user_id);
	}
	
	public Permissions getPermissionsByUser(String user_id){
		String hql =" from Permissions ps where ps.isValid = true and ps.user_id = ?0 ";
		return (Permissions) hibernateInvoker.findUnique(hql, user_id);
	}
	
}
